package com.nlscan.ncomgateway.core.remote

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import com.nlscan.ble.NlsBleManager
import com.nlscan.ble.connect.Connection
import com.nlscan.ble.util.NLogUtil
import com.nlscan.qdkit.common.core.util.BluetoothUtils
import com.nlscan.ncomgateway.core.model.entity.Device
import com.nlscan.ncomgateway.core.model.entity.asDevice

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/3/27
 *  desc  :
 * </pre>
 */
class DeviceRemoteDataSource(private val bleManager: NlsBleManager) {

    fun getDevices(): List<Device?> {
        return bleManager.connections.toList().map {
            it.second?.device?.asDevice()
        }
    }

    fun deleteDevice(address: String) {
        bleManager.removeDevice(address)
    }

    fun getConnection(address: String): Connection? =
        bleManager.getConnection(address)


    fun setAlias(device: Device, newName: String) {
        // TODO: 蓝牙开关没打开，获取不到已绑定设备信息
        //获取mac -> BluetoothDevice
        //todo 当前临时 catch，避免报错
        try {
            val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            val bondedDeviceSet = bluetoothAdapter.bondedDevices
            var findDevice: BluetoothDevice? = null
            for (item: BluetoothDevice in bondedDeviceSet) {
                if (device.address == item.address) {
                    findDevice = item
                    break
                }
            }
            if (findDevice != null) {
                // 查询信息
                NLogUtil.dTag("TAG21", "findDevice start name: ${findDevice.name}")

                var aliasName = BluetoothUtils.getAliasName(findDevice)
                NLogUtil.dTag("TAG21", "findDevice start aliasName: $aliasName")

                BluetoothUtils.setAliasName(findDevice, newName)
                aliasName = BluetoothUtils.getAliasName(findDevice)

                NLogUtil.dTag("TAG21", "findDevice rename aliasName: $aliasName")

            }
        } catch (e: Exception) {
            NLogUtil.e("setAlias error! msg: ${e.message}")
        }
    }

}